package cn.imu.controller;

import cn.imu.entity.User;
import cn.imu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Controller
@RequestMapping("/user")
public class UserController {
    //自动注入
    @Autowired
    private UserService userservice;
    //负责处理/index.html的请求
    @RequestMapping("/index.do")
    public String loginPage(){
        return "login";
    }

    //负责处理/loginCheck.html的请求
    @RequestMapping(value = "/loginCheck.do",method = RequestMethod.POST)
    public ModelAndView loginCheck(HttpServletRequest request,User user){
        System.out.println("进入loginCheck方法");
        System.out.println("loginCheck,userName="+user.getUser_name()+"  password="+user.getPassword());
        ModelAndView modelAndView=new ModelAndView();
        //调用service处理user
        boolean isVaildUser=userservice.hasMatchCount(user.getUser_name(),user.getPassword());
        if(!isVaildUser){
            modelAndView.addObject("error","用户名或密码错误");
            modelAndView.setViewName("login");
           return modelAndView;
        }else{
                 User user1=userservice.findUserByUserName(user.getUser_name());
                user1.setLast_ip(request.getRemoteAddr());
                user1.setLast_visit(new Date());
                userservice.loginSuccess(user1);
                request.getSession().setAttribute("user",user);
                return new ModelAndView("main");
            }
        }
    }

